<template>
    <div class="commonTab">
        <el-tabs v-model="value" type="card"
                 @tab-remove="removeTab"
                 @tab-click="handleClick">
            <template v-for="(row, index) in data">
                <el-tab-pane :name="row.name" :closable="row.closable">
                    <span slot="label"><i :class="row.icon"></i> {{row.label}}</span>
                    {{row.text}}
                </el-tab-pane>
            </template>
        </el-tabs>
    </div>
</template>
<script>
    export default {
        value: String,
        currentTab: String,

        data() {
            return {
                value: this.defaultValue
            };
        },
        constructor() {
        },
        watch:{
            defaultValue(val){
                this.value = val;
            }
        },
        methods: {
            handleClick(tab, event) {
                if( this.currentTab !== tab.name) {
                    this.currentTab = tab.name;
                    this.$emit("tabClick", tab, event);
                }
            },
            removeTab(tabName) {
                let tabs = this.data;
                let activeName = this.defaultValue;
                if (activeName === tabName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === tabName) {
                            let nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                this.value = nextTab.name;
                            }
                        }
                    });
                }
                this.data.forEach((tab, index) => {
                    if (tab.name === tabName) {
                        this.data.splice(index, 1);
                        return;
                    }
                });
                this.$emit("removeTab", tabName);
            },
            addTab(tab) {
//                this.$emit("addTab", tab);
            }
        },
        props: {
            data: {
                type: Array,
                default: function () {
                    return [];
                }
            },
            defaultValue: String
        }
    };
</script>